import React, { useState, useEffect, useRef } from 'react';
import { InputNumber, Input, message, Button, Select } from 'antd';
import CustomForm from 'src/components/CustomForm';
import TableEditor from 'src/components/TableEditor';
import * as events from 'src/utils/event/componentEvent';
import { compare } from 'src/utils/compare';

export default function ChallengeNode(props) {
  const { modes = [], actionType } = props;
  const { strategy_mode = '', name = '', nodes = [] } = props.value;
  const form = useRef(null);
  const [rules, setRules] = useState(nodes);
  const [strategyMode, setStrategyMode] = useState(strategy_mode);
  useEffect(() => {
    nodes.length > 0 && setRules(nodes);
  }, [nodes]);

  function openConfig(config, index) {
    if (!strategyMode) {
      message.warning('请先选择组件模式');
      return;
    }
    const compareData = props.compareData && props.compareData.nodes && props.compareData.nodes[index];
    events.eventEmitter.emit(events.OPEN_STRATEGY_NODE, {
      data: {
        ...config,
        strategy_mode: strategyMode,
        compareData: compareData,
        isCompare: props.isCompare,
        isOld: props.isOld,
      },
      actionType: props.actionType,
      nameDisabled: true,
      modelTitle: '编辑节点',
      cumstomAction: updateNode,
      isLimitMode: true,
    });
  }

  function updateNode(config, closeCallback) {
    const current = rules.find((rule) => rule.id === config.id);
    current.descr = config.descr;
    current.strategy_id = config.strategy_id;
    current.strategy_mode = config.strategy_mode;
    setRules(Object.assign([], rules));
    closeCallback && closeCallback();
  }

  function remove(index) {
    if (index <= 1) {
      return;
    }
    rules.splice(index, 1);
    rules.forEach((it, index) => {
      if (index >= 1) {
        it.name = '挑战者' + index;
      }
    });
    setRules(Object.assign([], rules));
  }

  function handleChangePercentInput(value, record, index) {
    rules[index] = { ...record, percent: value };
    setRules(Object.assign([], rules));
  }

  function changeHandlePercentInput(datas) {
    setRules(datas);
  }

  function handleSubmit() {
    form.current.validateFields((err, values) => {
      if (!err) {
        const total = rules.reduce((total, it) => {
          total += it.percent || 0;
          return total;
        }, 0);
        const params = {
          label: values.name,
          name: values.name,
          strategy_mode: strategyMode,
          nodes: rules,
        };
        try {
          if (total !== 100) {
            throw '百分比总和必须等于100%';
          }
          rules.forEach((item) => {
            if (item.strategy_mode === undefined || !item.strategy_id) {
              throw `请配置${item.name}节点`;
            }
          });
          props.onSubmit && props.onSubmit(params);
        } catch (err) {
          message.warning(err);
          return;
        } finally {
        }
      }
    });
  }

  function handleChangeMode(value) {
    setStrategyMode(value);
    // 清空rules strategy_id
    rules.forEach((it) => {
      delete it.strategy_id;
    });
    setRules(Object.assign([], rules));
  }

  const formItems = [
    {
      label: {
        label: '节点名称',
        className: 'tantuer-form-item3 tantuer-form-item-nowrap',
      },
      name: 'name',
      options: {
        initialValue: name,
        rules: [
          { required: true, message: '请输入节点名称' },
          { pattern: /^[\u4E00-\u9FA5_a-zA-Z0-9]+$/, message: '限中英文数字下划线' },
          { max: 128, message: '最长128个字符' },
        ],
      },
      component: <Input disabled={props.disabled} style={compare(props, 'name')} />,
    },
    {
      label: {
        label: '组件模式',
        className: 'tantuer-form-item3 tantuer-form-item-nowrap',
      },
      name: 'strategy_mode',
      options: {
        initialValue: strategyMode,
        rules: [{ required: true, message: '请选择组件模式' }],
      },
      component: (
        <Select
          style={{ width: '100%', ...compare(props, 'strategy_mode') }}
          placeholder='请选择'
          disabled={actionType === 'detail'}
          onChange={(value) => handleChangeMode(value)}
        >
          {modes &&
            modes.map((it) => {
              return (
                <Select.Option value={it.key} key={it.key}>
                  {it.value}
                </Select.Option>
              );
            })}
        </Select>
      ),
    },
  ].filter(Boolean);

  const columns = [
    {
      dataIndex: 'label',
      key: 'label',
      title: '挑战节点名',
      render: (text, record, index) => {
        return <>{text === '冠军' ? text : '挑战者' + index}</>;
      },
    },
    {
      dataIndex: 'percent',
      key: 'percent',
      title: '节点流量比例',
      width: 300,
      render: (text, record, index) => {
        // 查找出对比的节点数据
        const compareData = props.compareData && props.compareData.nodes && props.compareData.nodes[index];
        const compares = {
          isOld: props.isOld,
          value: record,
          isCompare: props.isCompare,
          compareData: compareData || {},
        };
        return (
          <>
            <InputNumber
              min={0}
              max={100}
              value={text || 0}
              formatter={(value) => `${value}%`}
              onChange={(value) => handleChangePercentInput(value, record, index)}
              disabled={props.disabled}
              style={compare(compares, 'percent')}
            />
            <span style={{ marginLeft: '10px' }}>(节点流量0%-100%)</span>
          </>
        );
      },
    },
  ];

  return (
    <div>
      <CustomForm
        colNum={2}
        createForm={(ref) => (form.current = ref)}
        formItems={formItems}
        onHandleSubmit={() => handleSubmit()}
        className='warning-setting'
        hideSubmit={props.disabled}
        confirmText='提交'
      >
        <div style={{ padding: '0 30px 20px 30px' }}>
          <TableEditor
            columns={columns}
            initItem={{
              shape: 'strategy',
              type: 'strategy',
              label: '挑战者' + rules.length,
              name: '挑战者' + rules.length,
              percent: 0,
              strategy_config: {
                mode: {},
              },
            }}
            dataSource={rules}
            onChange={changeHandlePercentInput}
            getButtonGroup={() => {
              return [
                (text, record, index) => {
                  // 查找出对比的节点数据
                  const compareData = props.compareData && props.compareData.nodes && props.compareData.nodes[index];
                  const compares = {
                    isOld: props.isOld,
                    value: record,
                    isCompare: props.isCompare,
                    compareData: compareData || {},
                  };
                  return (
                    <Button
                      type='link'
                      onClick={() => openConfig(record, index)}
                      className={props.disabled ? 'ant-btn-link-dark' : null}
                      style={compare(compares, 'strategy_id')}
                    >
                      {props.disabled ? '查看' : '配置'}
                    </Button>
                  );
                },
                (text, record, index) => {
                  return (
                    <Button type='link' onClick={() => remove(index)} disabled={props.disabled || index <= 1}>
                      删除
                    </Button>
                  );
                },
              ];
            }}
            noNeedAdd={props.disabled}
          />
        </div>
      </CustomForm>
    </div>
  );
}
